package oa.hleast.xswl.service.pms.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import oa.hleast.xswl.common.constant.OmsConstants;
import oa.hleast.xswl.common.constant.PmsConstants;
import oa.hleast.xswl.common.enums.CouponSourceEnum;
import oa.hleast.xswl.common.enums.LotteryEnum;
import oa.hleast.xswl.common.enums.PointOperatingEnum;
import oa.hleast.xswl.mapper.pms.PmsLotteryMapper;
import oa.hleast.xswl.pojo.domain.SysCommonConfig;
import oa.hleast.xswl.pojo.domain.pms.PmsLottery;
import oa.hleast.xswl.pojo.domain.pms.PmsUserLottery;
import oa.hleast.xswl.pojo.vo.SysCommonConfigVo;
import oa.hleast.xswl.service.ISysCommonConfigService;
import oa.hleast.xswl.service.IUmsUserService;
import oa.hleast.xswl.service.pms.PmsLotteryService;
import oa.hleast.xswl.service.pms.PmsUserCouponService;
import oa.hleast.xswl.service.pms.PmsUserLotteryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * @author: 00209
 * @date: 2021-06-15 15:58:03
 * @description: 奖品表(PmsLottery)接口实现
 */
@AllArgsConstructor
@Transactional
@Service("pmsLotteryService")
public class PmsLotteryServiceImpl extends ServiceImpl<PmsLotteryMapper, PmsLottery> implements PmsLotteryService {
    private final PmsUserLotteryService pmsUserLotteryService;

    private final IUmsUserService memberFeignService;

    private final PmsUserCouponService pmsUserCouponService;

    private final ISysCommonConfigService commonConfigService;

    @Override
    public PmsLottery draw(long userId) {

        // todo： 积分不够

        // todo: 优惠券可领取

        QueryWrapper<PmsLottery> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(sum(probability),0) as totalProbability").eq("status", 1);
        Map<String, Object> map = this.getMap(queryWrapper);
        BigDecimal sumProbability = (BigDecimal) map.get("totalProbability");


        List<PmsLottery> list = this.list(new LambdaQueryWrapper<PmsLottery>().eq(PmsLottery::getStatus, 1));
        if (list.size() == 0) {return new PmsLottery();}

        Long[] lotterys = new Long[100];
        int index = 0;
        for (PmsLottery pmsLottery : list) {
            int ratio = (pmsLottery.getProbability() * 100 / sumProbability.intValue());
            for (int i = 0; i < ratio; i++) {
                lotterys[index + i] = pmsLottery.getId();
            }
            index += ratio;
        }

        List<Long> lotterysList = Arrays.asList(lotterys);
        Collections.shuffle(lotterysList);

        int luckyNumber = RandomUtil.randomInt(100);
        long id = lotterysList.get(luckyNumber);


        SysCommonConfig lotteryRule = commonConfigService.getByConfigKey(PmsConstants.COMMON_CONFIG_LOTTERY_RULE);
        JSONObject jsonObject = JSONUtil.parseObj(lotteryRule.getValue());
        Long needPoints = jsonObject.getLong(PmsConstants.COMMON_CONFIG_LOTTERY_RULE_NEED_POINTS);

        // 用户记录表
        PmsUserLottery pmsUserLottery = new PmsUserLottery();
        pmsUserLottery.setUserId(userId);
        pmsUserLottery.setLotteryId(id);
        pmsUserLotteryService.save(pmsUserLottery);

        // 积分扣除
        memberFeignService.updatePoint(needPoints, PointOperatingEnum.POINT_LOTTERY_DRAW.getCode());
        PmsLottery pmsLottery;
        if (0 == id) {
            pmsLottery = new PmsLottery();
        } else {
            pmsLottery = this.getById(id);
            LotteryEnum lotteryEnum = LotteryEnum.getValue(pmsLottery.getType());
            pmsUserLottery.setType(pmsLottery.getType());
            pmsUserLottery.setName(pmsLottery.getName());
            pmsUserLotteryService.saveOrUpdate(pmsUserLottery);
            // todo: 获取奖品
            switch (lotteryEnum) {
                case POINT:
                    memberFeignService.updatePoint(pmsLottery.getRelationId(), PointOperatingEnum.POINT_LOTTERY_LUCKY.getCode());
                    break;
                case COUPON:
                    //
                    pmsUserCouponService.receive(pmsLottery.getRelationId(), userId, CouponSourceEnum.LOTTERY);
                    break;
            }
        }


        return pmsLottery;

    }
}
